package com.wframe.project.former.dataservices.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.frame.common.SystemConfig;
import com.frame.database.JBaseService;
import com.frame.database.JServiceFactory;
import com.frame.database.JdataBean;

public class UploadService extends JBaseService<UploadDao>{

	public static UploadService getIntance(){
        return (UploadService) JServiceFactory.createJServiceProxy(UploadService.class);
    }
	
	public String createFileDir(String dir) throws Exception{
    	String path=dir;
    	if(!path.endsWith("/"))path+="/";
    	JdataBean d=getDao().getSession().getObject("select * from app_filestat where dir like ? order by nums limit 0,1",new Object[]{path+"%"});
    	int num=0;
    	if(d==null){
    		path+="f1/";
    		File df=new File(SystemConfig.getInstance().getRootPath()+path);
    		try{df.mkdirs();}catch(Exception e){}
    	}else{
    		num=d.getInt("nums");
    		if(num>5000){
        		File df=new File(SystemConfig.getInstance().getRootPath()+path);
        		int len=df.listFiles().length;
        		path+="f"+(len+1)+"/";
        		File cf=new File(SystemConfig.getInstance().getRootPath()+path);
        		try{if(!cf.exists())cf.mkdirs();}catch(Exception e){}
        	}else path=d.getString("dir");
    	}
    	addFileDir(path);
    	return path;
    }
	
	public String saveFile(FileBean bean) throws Exception{
		return getDao().saveFile(bean);
	}
	
	public List<JdataBean> queryFiles(String userid,String dir) throws Exception{
		return getDao().queryFiles(userid, dir);
	}
	
	public List<JdataBean> queryFiles(String dataid) throws Exception{
		if(StringUtils.isNotBlank(dataid))
		return getDao().queryFiles(dataid);
		else return new ArrayList<JdataBean>();
	}
	
	public JdataBean getFile(String fid) throws Exception{
		return getDao().getFile(fid);
	}
	public String addPhoto(JdataBean p) throws Exception{
		return getDao().addPhoto(p);
	}

	public List<JdataBean> queryPhotos(String dataid) throws Exception{
		return getDao().queryPhotos(dataid);
	}
	public void setPhotoDataId(String dataid,String... photoid) throws Exception{
		getDao().setPhotoDataId(dataid,photoid);
	}
	public void clearPhotosNot(String dataid,String... files) throws Exception{
		getDao().clearPhotosNot(dataid,files);
	}
	public JdataBean getPhoto(String id) throws Exception{
		return getDao().getPhoto(id);
	}
	
	private void addFileDir(String dir) throws Exception{
    	int n=getDao().getSession().update("update app_filestat set nums=nums+1 where dir=?",new Object[]{dir});
    	if(n==0)getDao().getSession().update("insert into app_filestat(dir) values (?)",new Object[]{dir});
    }
}

